
package com.probiz.estore.system.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.common.model.system.Region;
import com.probiz.estore.common.model.system.RegionItem;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.system.dao.RegionDao;
import com.probiz.estore.system.dao.RegionItemDao;
import com.probiz.estore.system.model.UserDefinedRegionFullyModel;
import com.probiz.estore.system.service.RegionManager;

/**
 * Manager implementation for Region, responsible for business processing, and
 * communicate between web and persistence layer.
 */
public class RegionManagerImpl extends GenericManagerImpl<Region> implements
		RegionManager {

	private RegionDao	regionDao	= null;
	private RegionItemDao regionItemDao = null;

	/**
	 * @param regionDao
	 *            the regionDao to set
	 */
	public void setRegionDao(RegionDao regionDao) {
		this.regionDao = regionDao;
	}
	

	


	public void setRegionItemDao(RegionItemDao regionItemDao) {
		this.regionItemDao = regionItemDao;
	}





	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
	 */
	@Override
	protected void initManager() {
		dao = regionDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preDelete(java.lang.Object)
	 */
	@Override
	protected void preDelete(Region entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preSave(java.lang.Object)
	 */
	@Override
	protected void preSave(Region entity) {

	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#getDefaultRootRegion()
	 */
	public Region getDefaultRootRegion(){
		return this.regionDao.getById(Constants.REGIONID_CHINA);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#updateRegionsSortOrder(java.lang.Integer[])
	 */
	public void updateRegionsSortOrder(Integer[] regionIds){
		for (int i = 0; i < regionIds.length; i++) {
			Integer regionId = regionIds[i];
			Region region=getById(regionId);
			if(region==null)continue;
			try {
				BeanUtils.setProperty(region,"sortOrder",(i+1));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			save(region);
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#deleteFully(com.probiz.estore.common.model.system.Region)
	 */
	public Map<String, Object> deleteFully(Region region){
		Map<String, Object> returnMsgs = new HashMap<String, Object>();
    	returnMsgs.put("regionId", region.getRegionId());
    	List<Region> userSubRegion = this.getUserSubRegion(region.getRegionId());
		if (Constants.REGIONID_WORLD.equals(region.getRegionId()) || Constants.REGIONID_CHINA.equals(region.getRegionId())) {
			// case:如果是根地区
			returnMsgs.put("result", -1);
			returnMsgs.put("message", I18nUtil.getInstance().getMessage("region.del.root"));
		} else if (region.getChildren().size()>0) {
			// case:如果包含子地区
			returnMsgs.put("result", -2);
			returnMsgs.put("message",I18nUtil.getInstance().getMessage("region.del.containSubCat"));
		} else if (userSubRegion.size()>0) {
			// case:如果包含自定义地区
			returnMsgs.put("result", -3);
			returnMsgs.put("message",I18nUtil.getInstance().getMessage("region.del.containDefined"));
		} else {
			// otherwise:成功删除-----逻辑删除：因为订单地址、客户地址、运输费率、税率等非常多的都需要用到。
			Integer parentId = region.getParentId();
			// 获得父id
			region.setStatus(Constants.FLAG_FALSE);
	        regionDao.save(region);
			returnMsgs.put("result", 1);
			returnMsgs.put("message", I18nUtil.getInstance().getMessage("region.del.success"));
			returnMsgs.put("parentId", parentId);
		}
    	
		return returnMsgs;
		 
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#saveFully(com.probiz.estore.common.model.system.Region)
	 */
	public void saveFully(Region entity){
		entity.setStatus(Constants.FLAG_TRUE);
		if(entity.getRegionId()== null){
			Region parent = this.getById(entity.getParentId());
			entity.setRegionType(parent.getRegionType()+1);
		}
		if (null == entity.getRegionId()) {
            //case:新增
            entity.setSortOrder(Region.SORTORDER_DEFAULT_VALUE);
        }
		this.save(entity);
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.system.service.RegionManager#getUserSubRegion(java.lang.Integer)
	 */
	public List<Region> getUserSubRegion(Integer regionId) {
		ArrayList<Region> result = new ArrayList<Region>();
		Region region = this.regionDao.getById(regionId);
		Set<RegionItem> regionItemSet = region.getRegionItems();
		for (RegionItem regionItem : regionItemSet) {
			result.add(regionItem.getItem());
		}
		return result;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#getAllUserDefinedRegion()
	 */
	public List<Region> getAllUserDefinedRegion(){
		return regionDao.findByHql("from Region where regionType=? and status=?", new Object[]{Constants.REGIONI_TYPE_USERDEFINED,Constants.FLAG_TRUE});
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#deleteFullyForUserDefinedType(com.probiz.estore.common.model.system.Region)
	 */
	public void deleteFullyForUserDefinedType(Region entity){
		entity.setStatus(Constants.FLAG_FALSE);
		regionDao.save(entity);
		for(RegionItem item: (Set<RegionItem>)entity.getRegionItems()){
			regionItemDao.delete(item);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#saveFullyForUserDefinedType(com.probiz.estore.system.model.UserDefinedRegionFullyModel)
	 */
	public void saveFullyForUserDefinedType(UserDefinedRegionFullyModel model){
		Region entity = model.getRegion();
		entity.setStatus(Constants.FLAG_TRUE);
		entity.setRegionType(Constants.REGIONI_TYPE_USERDEFINED);
		entity.setSortOrder(Region.SORTORDER_DEFAULT_VALUE);
		regionDao.save(entity);
		regionItemDao.saveRegionItemsFromArrays(entity, model.getRegionItemIds(), model.getRegionItemItemIds());
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.RegionManager#getChildrenByRegionId(Integer)
	 */
	public Set<Region> getChildrenByRegionId(Integer regionId){
		List<Region> regionList = regionDao.findByHql("from Region r where r.parent.regionId = ? and r.status != 0 order by r.sortOrder asc", regionId);
		Set<Region> regionSet = new LinkedHashSet<Region>();
		regionSet.addAll(regionList);
		return regionSet;
	}


}
